<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>防抖</title>
  <style>
    .container {
      width: 500px;
      height: 500px;
      background-color: antiquewhite;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 auto;
    }
  </style>
</head>

<body>
  <div class="container">
    0
  </div>
  <script>
    let container = document.querySelector('.container')
    var count = 0

    function getLocation(e) {
      console.log(this);
      console.log(e);
      container.innerHTML = count++
    }

    container.onmousemove = debounce(getLocation, 1000, true)

    //版本一,只有在等待传入的时间后才会执行
    function debounce(fun, wait, immediate=false) {
      var timeout = null
      return function () {
        let arg = arguments
        let that = this
        if (timeout) clearTimeout(timeout)
        if (immediate) {
          let callNow = !timeout
          timeout = setTimeout(function () { timeout = null },wait)
          if(callNow) fun.apply(that,arg)
        } else {
          timeout = setTimeout(function () {
            fun.apply(that, arg)
          }, wait)
        }

      }
    }
  </script>
</body>

</html>